<template>
  <div class="divBox">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <el-tabs v-model="tableFrom.type" @tab-click="seachList">
          <el-tab-pane :label="item.name +'('+item.count +')' " :name="item.type.toString()" v-for="(item,index) in headeNum" :key="index"/>
        </el-tabs>
        <div class="container">
          
          <el-form inline size="small">
            <el-row>
              <el-form-item label="商品分类：">
                <el-cascader v-model="tableFrom.cateId" :options="merCateList" :props="props" clearable class="selWidth mr20" @change="seachList" size="small"/>
              </el-form-item>
              <el-form-item label="商品搜索：">
                <el-input v-model="tableFrom.keywords" placeholder="请输入商品名称，关键字，商品ID" class="selWidth" size="small">
                </el-input>
              </el-form-item>
              <el-form-item label="小编推荐:">
                <el-checkbox v-model="tableFrom.isBest"></el-checkbox>
              </el-form-item>
              <el-form-item label="易时尚商品:">
                <el-checkbox v-model="tableFrom.merUse"></el-checkbox>
              </el-form-item>
              <el-form-item label="意大利商品:">
                <el-checkbox v-model="tableFrom.isEurope"></el-checkbox>
              </el-form-item>
              </el-row>
            <el-row>
              <el-form-item label="品牌：">
                <el-select v-model="tableFrom.brandId"  filterable placeholder="请选择">
                  <el-option
                    v-for="item in brandList"
                    :key="item.brandId"
                    :label="item.brandName"
                    :value="item.brandId">
                    {{item.brandName}}  [{{item.productCount}}]
                  </el-option>
                </el-select>
              </el-form-item>
              
              <el-form-item>
                
                <el-checkbox-group v-model="stockAreas">
                  <el-checkbox label="1" key="1">大陆</el-checkbox>
                  <el-checkbox label="2" key="2">港澳</el-checkbox>
                  <el-checkbox label="3" key="3">欧洲</el-checkbox>
                </el-checkbox-group>
              </el-form-item>
              <el-form-item class="text-right">
                  <el-button type="primary" icon="ios-search" label="default" class="mr15" size="small"   @click="seachList">搜索</el-button>
              </el-form-item>
            </el-row>
          </el-form>
        </div>
       
        <router-link :to=" { path:'/store/list/creatProduct' } ">
          <el-button size="small" type="primary" class="mr10">添加商品</el-button>
        </router-link>
        <!-- <el-button size="small" type="success" class="mr10" @click="onCopy">复制淘宝、天猫、拼多多、京东、苏宁</el-button> -->
        <el-button size="small" @click="exports">导出</el-button>
      </div>
      <el-table
        v-loading="listLoading"
        :data="tableData.data"
        style="width: 100%"
        size="mini"
        highlight-current-row
      >
        <el-table-column type="expand">
          <template slot-scope="props">
            <el-table
              :data="props.row.attrValue"
              style="width: 100%"
              >
              <el-table-column
                fixed
                prop="suk"
                label="规格"   
                width="150">
              </el-table-column>
              <el-table-column
                prop="price"
                label="售价"
                width="120">
              </el-table-column>
              <el-table-column
                prop="cost"
                label="成本价"
                width="120">
              </el-table-column>
              <el-table-column
                prop="otPrice"
                label="原价"
                width="120">
              </el-table-column>
              <el-table-column
                prop="stock"
                label="库存"
                sortable
                width="300">
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>
        <el-table-column
          prop="id"
          label="ID"
          min-width="60"
        />
        <el-table-column label="商品图" min-width="100">
          <template slot-scope="scope">
            <div class="demo-image__preview">
              <el-image
               style="width: 100px !important; height: 100px !important"
                :src="scope.row.image"
                :preview-src-list="JSON.parse(scope.row.sliderImage)"
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="商品名称"
          min-width="200">
          <template slot-scope="scope">
            <el-tag effect="dark" type="danger" size="mini" v-if="scope.row.merUse">Y</el-tag>
            <span>{{scope.row.storeName}}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="keyword"
          label="商品编码"
          min-width="180"
        />
        <el-table-column
          prop="price"
          label="售价(RMB)"
          min-width="90"
        />
        <el-table-column
          prop="cost"
          label="成本价(RMB)"
          min-width="90"
        />
        <el-table-column
          prop="otPrice"
          label="原价(RMB)"
          min-width="90"
        />
        <el-table-column
          prop="postage"
          label="运税费(国内收)"
          min-width="120"
        />
        <el-table-column
          label="推荐"
          min-width="100"
        >
          <template slot-scope="scope">
            <el-switch
              :disabled="tableFrom.type === '5'"
              v-model="scope.row.isBest"
              :active-value="true"
              :inactive-value="false"
              active-text="推荐"
              inactive-text="推荐"
              @change="onchangeIsBest(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column
          prop="sales"
          label="销量"
          min-width="70"
        />
        <el-table-column
          prop="stock"
          label="库存"
          min-width="70"
        />
        <el-table-column
          prop="tempId"
          label="发货地"
          min-width="70"
        >
         <template slot-scope="scope">
            <span>{{scope.row.tempId|stockArea(that)}}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="状态"
          min-width="100"
        >
          <template slot-scope="scope">
            <el-switch
              :disabled="tableFrom.type === '5'"
              v-model="scope.row.isShow"
              :active-value="true"
              :inactive-value="false"
              active-text="上架"
              inactive-text="下架"
              @change="onchangeIsShow(scope.row)"
            />
          </template>
        </el-table-column>
        
        <el-table-column
          label="操作时间"
          min-width="120"
        >
          <template slot-scope="scope">
            <span>{{scope.row.addTime | formatDate}}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="120" fixed="right" align="center">
          <template slot-scope="scope">
            <router-link :to="{path: '/store/list/creatProduct/' + scope.row.id}">
              <el-button type="text" size="small" class="mr10">编辑</el-button>
            </router-link>
            <el-button  v-if="tableFrom.type === '5'" type="text" size="small" @click="handleRestore(scope.row.id, scope.$index)">恢复商品</el-button>
            <el-button type="text" size="small" @click="handleDelete(scope.row.id, scope.$index)">{{ tableFrom.type === '5' ? '删除' : '加入回收站' }}</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination
          :page-sizes="[20, 40, 60, 80]"
          :page-size="tableFrom.limit"
          :current-page="tableData.page"
          layout="total, sizes, prev, pager, next, jumper"
          :total="tableData.total"
          @size-change="handleSizeChange"
          @current-change="pageChange"
        />
      </div>
    </el-card>

    <el-dialog
      title="复制淘宝、天猫、拼多多、京东、苏宁"
      :visible.sync="dialogVisible"
      width="1200px"
      :before-close="handleClose">
      <tao-bao v-if="dialogVisible"></tao-bao>
    </el-dialog>
  </div>
</template>

<script>
import { setIsBest,productLstApi, productDeleteApi, categoryApi, putOnShellApi, offShellApi, productHeadersApi, productExportApi, restoreApi } from '@/api/store'
import { getToken } from '@/utils/auth'
import taoBao from './taoBao'
import { brandList } from '@/api/brand'
export default {
  name: 'ProductList',
  components: { taoBao },
  data() {
    return {
      that:this,
      props: {
        children: 'child',
        label: 'name',
        value: 'id',
        emitPath: false
      },
      // roterPre: roterPre,
      headeNum: [],
      listLoading: true,
      tableData: {
        data: [],
        total: 0,
        page:1
      },
      isFromEdit:false,
      tableFrom: {
        page: 1,
        limit: 20,
        cateId: '',
        brandId:'',
        keywords: '',
        isBest:'',
        merUse:'',
        isEurope:'',
        stockAreas:'',
        type: '1'
      },
      stockAreaList:{
                1:"大陆",
                2:"港澳",
                3:"欧洲"
              },
      stockAreas:[],
      brandList: [], // 品牌列表
      categoryList: [],
      merCateList: [],
      objectUrl: process.env.VUE_APP_BASE_API,
      dialogVisible: false
    }
  },
  mounted() {
    this.goodHeade()
    this.getCategorySelect()
    this.getBrandList()
  },
  beforeRouteEnter(to,from,next) {
      next(vm=>{
        if (from.name == "SortCreat"){
          vm.isFromEdit=true;
        }
        vm.getList()
      }) 
  },
  filters: {
    stockArea(val,that) {
      return that.stockAreaList[val];
    }
  },
  methods: {
    handleRestore(id) {
      this.$modalSure("恢复商品").then(() => {
        restoreApi(id)
          .then((res) => {
            this.$message.success('操作成功');
            this.goodHeade();
            this.getList();
          })
      });
    },
    // 品牌列表；
    getBrandList() {
      brandList(this.tempData).then(res => {
        this.brandList = res;
      })
    },
    seachList() {
      this.tableFrom.page = 1
      this.getList()
    },
    //设置cookie
    setCookie(name, value, day){
        if (day !== 0) {
            var expires = day * 24 * 60 * 60 * 1000;
            var date = new Date(+new Date() + expires);
            document.cookie = name + "=" + escape(JSON.stringify(value)) + ";expires=" + date.toUTCString();
        } else {
            document.cookie = name + "=" + + escape(JSON.stringify(value));
        }
    },
    //获取cookie
    getCookie(name){
        var arr;
        var reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
        if (arr = document.cookie.match(reg))
            return JSON.parse(unescape(arr[2]));
        else 
            return null
    },
    handleClose() {
      this.dialogVisible = false
    },
    // 复制
    onCopy(){
      this.dialogVisible = true
    },
    // 导出
    exports () {
      let url="";
      for( let i in this.tableFrom){
        url+="&"+i+"="+this.tableFrom[i]
      }
      window.open(this.objectUrl + '/api/admin/export/excel/product?Authori-zation=' + getToken()+url);
    },
    // 获取商品表单头数量
    goodHeade () {
      productHeadersApi().then(res => {
        this.headeNum = res
      }).catch(res => {
        this.$message.error(res.message);
      })
    },
    // 商户分类；
    getCategorySelect() {
      categoryApi({ status: -1, type: 1 }).then(res => {
        this.merCateList = res
      }).catch(res => {
        this.$message.error(res.message)
      })
    },
    // 列表
    getList() {
      if(this.isFromEdit){
        var filter = this.getCookie("searchFilter");
        if (JSON.stringify(filter) != "{}") {
            //this.getList();
            this.tableFrom = filter;
            this.stockAreas=this.tableFrom.stockAreas.split(",");
        };
      }else{
        this.tableFrom.stockAreas=this.stockAreas.join(",");
      }
      this.listLoading = true
      this.isFromEdit=false;
      this.setCookie('searchFilter',this.tableFrom,1);
      productLstApi(this.tableFrom).then(res => {
        this.tableData.data = res.list
        this.tableData.total = res.total
        this.tableData.page = res.page
        this.listLoading = false
      }).catch(res => {
        this.listLoading = false
        this.$message.error(res.message)
      })
    },
    pageChange(page) {
      this.tableFrom.page = page
      this.getList()
    },
    handleSizeChange(val) {
      this.tableFrom.limit = val
      this.getList()
    },
    // 删除
    handleDelete(id, idx) {
      this.$modalSure().then(() => {
        productDeleteApi(id).then(() => {
          this.$message.success('删除成功')
          this.getList()
        })
      })
    },
    onchangeIsShow(row) {
      row.isShow
        ? putOnShellApi( row.id ).then(() => {
          this.$message.success('上架成功')
          this.getList()
        }) : offShellApi(row.id).then(() => {
          this.$message.success('下架成功')
          this.getList()
        })
    },
    onchangeIsBest(row) {
      console.log(row);
      setIsBest({productId:row.id,isBest:row.isBest}).then(() => {
          this.$message.success('打标成功')
          // 不处理异常情况
      });
    }
  }
}
</script>

<style scoped lang="scss">
  .demo-table-expand{
    /deep/ label{
      width: 82px;
    }
  }
  .demo-table-expand{
    /deep/ .el-form-item__content{
      width: 77%;
    }
  }
  .selWidth{
    width: 350px !important;
  }
  .seachTiele{
    line-height: 30px;
  }
</style>
